<template>
  <div class="register">
    <el-dialog width="600px" :visible.sync="isShow" :show-close="false">
      <div slot="title" class="title">用户注册</div>
      <el-form label-width="100px" :model="form" :rules="rules" ref="form">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            name="image"
            class="avatar-uploader"
            :action="baseUrl+'/uploads'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="baseUrl+'/'+form.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="昵称">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item prop="code" label="图形码">
          <el-row>
            <el-col :span="15">
              <el-input v-model="form.code"></el-input>
            </el-col>
            <el-col :span="8" :offset="1">
              <img :src="baseUrl +'/'+ codeUrl" alt class="img-code" @click="getCodeUrl" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="rcode" label="验证码">
          <el-row>
            <el-col :span="15">
              <el-input v-model="form.rcode"></el-input>
            </el-col>
            <el-col :span="8" :offset="1">
              <el-button class="btn" @click="getRcode" :disabled="totalTime!=6">
                获取用户验证码
                <span v-if="totalTime!=6">({{totalTime}})s</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getCodeApi, toRegister } from "@/api/register.js";
export default {
  
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
      }
    },
  },
  data() {
    return {
      isShow: false,
      /*  imageUrl:'', */
      baseUrl: process.env.VUE_APP_URL,
      totalTime: 6,
      codeUrl: "/captcha?type=sendsms&",
      form: {
        username: "",
        phone: "",
        email: "",
        avatar: "",
        password: "",
        rcode: "",
        code: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号"));
              }
            },
          },
        ],
        email: [{ required: true, message: "请输入邮箱", trigger: "change" }],
        avatar: [{ required: true, message: "请填入头像", trigger: "change" }],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
        ],
        rcode: [{ required: true, message: "请输入图形码", trigger: "change" }],
        code: [{ required: true, message: "请输入验证码", trigger: "change" }],
      },
    };
  },
  methods: {
    getRcode() {
      let _num = 0;
      //验证手机号码与图形码
      this.$refs.form.validateField(["phone", "code"], (errMessage) => {
        if (errMessage == "") {
          _num++;
        }
      });
      if (_num == 2) {
        /*  alert('验证通过'); */
        this.totalTime--;
        let _time = setInterval(() => {
          this.totalTime--;
          if (this.totalTime <= 0) {
            clearInterval(_time);
            this.totalTime = 6;
          }
        }, 1000);
        //
        getCodeApi({
          code: this.form.code,
          phone: this.form.phone,
        }).then((res) => {
          this.$message.success(res.data.data.captcha + "");
          window.console.log("手机验证码",res);
        })
        
      }
    },
    getCodeUrl() {
      this.codeUrl = "/captcha?type=sendsms&" + Math.random();
    },
    submit() {
      this.$refs.form.validate((res) => {
        if (res) {
         
          toRegister(this.form).then(() => {
           
              this.$message.success("注册成功");
              this.isShow = false;
            
          });
        } else {
          this.$message.error("验证失败");
        }
      });
    },
    handleAvatarSuccess(res /* , file */) {
      /*  this.imageUrl = URL.createObjectURL(file.raw); */
      this.form.avatar = res.data.file_path;
      console.log(this.form.avatar);
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG,png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="less">
.register {
  .img-code {
    width: 100%;
    height: 40px;
  }
  .btn {
    width: 100%;
  }
  .title {
    background: linear-gradient(to right, #01c3fa, #1296fa);
    height: 43px;
    text-align: center;
    line-height: 43px;
    color: #fff;
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .footer {
    text-align: center;
  }
  .avatar-uploader {
    text-align: center;
  }
}
</style>